﻿using System;
using System.Linq;
using System.Threading.Tasks;
using System.Transactions;
using WalkingTec.Mvvm.Core;
using HengTong.Model.Db.Hr.Bill;
using Microsoft.EntityFrameworkCore;
using TiaoTaoHelper.Wtm.Models;
using UUIDNext;


namespace HengTong.ViewModel.Hr.SysHrStaffNeedRequestBillEntryVms
{
    public partial class SysHrStaffNeedRequestBillEntryVm : BaseCRUDVM<SysHrStaffNeedRequestBillEntry>
    {
        public SysHrStaffNeedRequestBillEntryVm()
        {
            SetInclude(x => x.Org);
            SetInclude(x => x.Group);
            SetInclude(x => x.JobPosition);
            SetInclude(x => x.HrStaffNeed);
        }

        protected override void InitVM()
        {
        }

        public override async Task DoAddAsync()
        {
            // 校验OrgId是否与主表一致
            await ValidateOrgIdConsistency();

            if (!MSD.IsValid)
                return;

            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            // 校验OrgId是否与主表一致
            await ValidateOrgIdConsistency();

            if (!MSD.IsValid)
                return;

            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoEditAsync(updateAllFields);
        }

        /// <summary>
        /// 必须使用异步事务, 否则工作流引擎会和当前事务冲突
        /// </summary>
        /// <param name="upAllFields"></param>
        public async Task ApproveAsync(bool upAllFields = false)
        {
            using var transactionScope = new TransactionScope(
                TransactionScopeOption.Required,
                new TransactionOptions
                {
                    IsolationLevel = IsolationLevel.ReadCommitted,
                    Timeout = TimeSpan.FromMinutes(10) // 增加超时时间到10分钟
                },
                TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                if (Entity is IFlow flow)
                {
                    flow.Approver = Wtm.LoginUserInfo?.ITCode;
                    flow.ApprovalTime = DateTime.Now;
                }

                await base.DoEditAsync(upAllFields);
                if (MSD.IsValid)
                {
                    await ContinueWorkflowAsync(ActionName, Remark);
                    if (MSD.IsValid)
                    {
                        transactionScope.Complete(); // 提交事务
                    }
                }
                // 如果到这里，事务会自动回滚
            }
            catch (Exception e)
            {
                // TransactionScope会自动回滚，无需手动操作
                MSD.AddModelError(" ", $"审批操作异常: {e.Message}");
            }
        }

        public override void DoDelete()
        {
            base.DoDelete();
        }

        private async Task ValidateOrgIdConsistency()
        {
            if (Entity.HrStaffNeedId.HasValue)
            {
                var masterBill = await DC.Set<SysHrStaffNeedRequestBill>()
                    .Where(x => x.ID == Entity.HrStaffNeedId.Value)
                    .FirstOrDefaultAsync();

                if (masterBill != null && masterBill.OrgId != Entity.OrgId)
                {
                    MSD.AddModelError("OrgId", "公司不一致，请重新选择");
                }
            }
        }
    }
}